<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="showInsert"
        >{{ $t('insert') }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="port"
          @change="sensorChange"
        >
          <el-option
            v-for="item in sensorList"
            :key="item.port"
            :label="item.sensorName + ' ['+$t('port')+':'+item.port+']'"
            :value="item.port"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="listSensorWith">{{ $t('search') }}</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="deviceSettingVisibleList"
      style="width: 100%"
    >
      <el-table-column
        :label="$t('name')"
      >
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.keyName"
            filterable
            :placeholder="$t('name')"
            disabled
          >
            <el-option
              v-for="item in settingList"
              :key="item.keyName"
              :label="item.name"
              :value="item.keyName"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :label="$t('value')">
        <template slot-scope="scope">
          <div v-if="scope.row.type === 'fixedParam' && scope.row.paramList && scope.row.paramList.length > 0">
            <span
              v-for="(param,index) in scope.row.paramList"
              v-if="param.value === scope.row.value"
              :key="index"
            >{{ param.name }} <span>({{ param.value }})</span></span>
          </div>
          <span v-else-if="scope.row.type === 'switch'">{{ scope.row.value === '1' ? $t('open') : $t('close') }} <span>({{
            scope.row.value
          }})</span></span>
          <span v-else>{{ scope.row.value }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('keyName')"
      >
        <template slot-scope="scope">
          <el-tag
            v-for="keyName in scope.row.keyNameList"
            :key="keyName"
            size="medium"
            style="margin-right: 5px"
          >
            {{ formatSettingName(keyName) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="$t('status')" width="70">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status?'success':'danger'"
            @click="changeStatus(scope.row)"
            v-text="scope.row.status ? $t('enable'):$t('stop')"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('function')" width="150">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="edit(scope.row)"
          >{{ $t('edit') }}
          </el-button>
          <el-button
            style="color: #f56c6c"
            type="text"
            icon="el-icon-delete"
            @click="del(scope.row)"
          >{{ $t('delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="dialogDeviceSettingVisibleVisible"
      top="15px"
      :title="$t('port')+':'+deviceSettingVisible.port"
    >
      <el-form
        label-width="20%"
        :model="deviceSettingVisible"
      >
        <el-form-item :label="$t('name')">
          <el-select
            v-model="deviceSettingVisible.keyName"
            filterable
            :placeholder="$t('name')"
            @change="keyNameChange"
          >
            <el-option
              v-for="item in settingList"
              :key="item.keyName"
              :disabled="item.type === 'noParam'"
              :label="item.name"
              :value="item.keyName"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="setting.settingId && setting.type !== 'noParam'" :label="$t('value')">
          <div v-if="setting.type === 'fixedParam'">
            <el-select
              v-model="deviceSettingVisible.value"
            >
              <el-option
                v-for="item2 in setting.paramList"
                :key="item2.value"
                :label="item2.name"
                :value="item2.value"
              />
            </el-select>
          </div>
          <div v-else-if="setting.type === 'switch'">
            <el-switch
              v-model="deviceSettingVisible.value"
              :active-text="$t('open')"
              :inactive-text="$t('close')"
              active-value="1"
              inactive-value="0"
            />
          </div>
          <div v-else-if="setting.type === 'time'">
            <el-time-picker
              v-model="deviceSettingVisible.value"
              value-format="HH:mm"
              format="HH:mm"
            />
          </div>
          <div v-else-if="setting.type === 'timeSlot'">
            <time-slot v-model="deviceSettingVisible.value" />
          </div>
          <div v-else-if="setting.type === 'slider'">
            <el-slider
              v-model="deviceSettingVisible.value"
            />
          </div>
          <div v-else="">
            <el-input
              v-model="deviceSettingVisible.value"
            />
          </div>
        </el-form-item>
        <el-form-item v-if="setting.settingId" :label="$t('show')">
          <el-tag
            v-for="keyName in deviceSettingVisible.keyNameList"
            :key="keyName"
            size="medium"
            style="margin-right: 5px"
            closable
            @close="deleteKeyName(keyName)"
          >
            {{ formatSettingName(keyName) }}
          </el-tag>
          <el-select
            v-if="showKeyNameSelect"
            v-model="keyNameValue"
            @change="keyNameSelect"
          >
            <el-option
              v-for="item in settingList"
              :key="item.keyName"
              :disabled="deviceSettingVisible.keyName === item.keyName"
              :label="item.name"
              :value="item.keyName"
            />
          </el-select>
          <el-button
            v-else
            type="primary"
            icon="el-icon-plus"
            @click="showKeyNameSelect = true"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDeviceSettingVisibleVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="addOrUpdate">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { cancelNotice, failureNotice, formatDate, successNotice } from '@/util/common'
import {
  deleteDeviceSettingVisible,
  insertDeviceSettingVisible,
  listDeviceSettingVisible,
  updateDeviceSettingVisible
} from '@/api/iot/iotDeviceSettingVisibleApi'
import { listSensorWith } from '@/api/iot/iotDeviceSensorApi'
import TimeSlot from '@/components/TimeSlot'

export default {
  name: 'SettingVisible',
  components: {
    TimeSlot
  },
  data() {
    return {
      deviceSettingVisibleList: [],
      deviceSettingVisible: {},
      dialogDeviceSettingVisibleVisible: false,
      sensorList: [],
      port: null,
      settingList: [],
      showKeyNameSelect: false,
      keyNameValue: null,
      setting: {}
    }
  }, created() {
    const param = this.$route.query
    this.deviceCore = param.deviceCore
    this.deviceName = param.deviceName
    this.listSensorWith()
    this.setTagsViewTitle()
  },
  methods: {
    keyNameChange() {
      for (const setting of this.settingList) {
        if (setting.keyName === this.deviceSettingVisible.keyName) {
          this.deviceSettingVisible.port = setting.port
          this.deviceSettingVisible.type = setting.type
          this.deviceSettingVisible.value = setting.value
          this.setting = setting
          return
        }
      }
    },
    formatSettingName(keyName) {
      for (const setting of this.settingList) {
        if (setting.keyName === keyName) {
          return setting.name
        }
      }
    },
    keyNameSelect() {
      if (this.deviceSettingVisible.keyName === this.keyNameValue || this.deviceSettingVisible.keyNameList.indexOf(this.keyNameValue) >= 0) {
        failureNotice(this)
        return
      }
      this.deviceSettingVisible.keyNameList.push(this.keyNameValue)
    },
    deleteKeyName(keyName) {
      for (let i = 0, j = this.deviceSettingVisible.keyNameList.length; i < j; i++) {
        if (this.deviceSettingVisible.keyNameList[i] === keyName) {
          this.deviceSettingVisible.keyNameList.splice(i, 1)
        }
      }
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    listSensorWith() {
      listSensorWith({
        deviceCore: this.deviceCore,
        withSetting: true
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.sensorList = data
          if (!this.port) {
            const item = data[0]
            this.deviceId = item.deviceId
            this.port = item.port
            this.settingList = item.settingList
          } else {
            for (const sensor of data) {
              if (sensor.port === this.port) {
                this.settingList = sensor.settingList
              }
            }
          }
        } else {
          this.sensorList = []
          this.settingList = []
        }
        this.listDeviceSettingVisible()
      })
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    showInsert() {
      this.deviceSettingVisible = {
        deviceId: this.deviceId,
        port: this.port,
        keyNameList: []
      }
      this.dialogDeviceSettingVisibleVisible = true
    },
    sensorChange() {
      this.listSensorWith()
    },
    listDeviceSettingVisible() {
      listDeviceSettingVisible({
        deviceCore: this.deviceCore,
        port: this.port
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          data.forEach(item => {
            this.settingList.forEach(setting => {
              if (item.keyName === setting.keyName) {
                item.type = setting.type
                item.paramList = setting.paramList
              }
            })
          })
          this.deviceSettingVisibleList = data
        } else {
          this.deviceSettingVisibleList = []
        }
      })
    },
    changeStatus(item) {
      const data = {
        visibleId: item.visibleId,
        status: !item.status
      }
      updateDeviceSettingVisible(data).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listDeviceSettingVisible()
      })
    },
    addOrUpdate() {
      const json = {
        ...this.deviceSettingVisible
      }
      if (!json.visibleId) {
        insertDeviceSettingVisible(json).then(res => {
          const { code } = res
          if (code === '200') {
            this.dialogDeviceSettingVisibleVisible = false
          }
          this.listDeviceSettingVisible()
        })
      } else {
        updateDeviceSettingVisible(json).then(res => {
          const { code } = res
          if (code === '200') {
            this.dialogDeviceSettingVisibleVisible = false
          }
          this.listDeviceSettingVisible()
        })
      }
    },
    edit(item) {
      this.deviceSettingVisible = item
      for (const setting of this.settingList) {
        if (setting.keyName === item.keyName) {
          this.setting = setting
          if (setting.type === 'slider') {
            this.deviceSettingVisible.value = parseInt(setting.value)
          }

          break
        }
      }
      this.dialogDeviceSettingVisibleVisible = true
    },
    del(item) {
      const that = this
      this.$confirm(this.$t('delete') + item.name, this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteDeviceSettingVisible({
            visibleId: item.visibleId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
              that.listDeviceSettingVisible()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    }
  }
}
</script>

